﻿using BaseUi.Device;
using HandyControl.Controls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Ping9719.WpfEx;
using Ping9719.WpfEx.Mvvm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Markup;
using Ping9719.DeviceCommunication.Clients.Modbus;
using System.Windows.Forms;
using MessageBox = HandyControl.Controls.MessageBox;

namespace BaseUi.ViewModel
{
    public class MainViewModel : BindableBase
    {
        Mutex mutex;
        private string title = string.Empty;
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get => title; set { SetProperty(ref title, value); } }

        #region 专用_MainWindow2
        //隐藏式选项卡的高度
        public double TabItemHeight { get; set; } = 0;

        private string SelectedValue_ = "主页";
        public string SelectedValue { get => SelectedValue_; set { SetProperty(ref SelectedValue_, value); } }
        #endregion

        private DateTime time;
        /// <summary>
        /// 时间
        /// </summary>
        public DateTime Time { get => time; set { SetProperty(ref time, value); } }
        /// <summary>
        /// 在初始化前的相关检查
        /// </summary>
        public bool InitAgo()
        {
            //只允许打开一个
            mutex = new Mutex(true, string.Concat("MengXunBaseUi", Path.GetFileNameWithoutExtension(LocalFile.AppName)), out bool createdNew);
            if (!createdNew)
            {
                MessageBox.Warning("已有实列在运行！", "提示");
                return false;
            }

            //初始化
            Tuple<string, string, Action>[] tuples = new Tuple<string, string, Action>[]
            {
                new Tuple<string, string, Action>("检测文件..", "缺少文件，尝试将项目[data/]中的所有文件复制到[bin/data/]中", () =>
                {
                    if(!System.IO.File.Exists(LocalFile.ConfigPath)||!System.IO.File.Exists(LocalFile.PlcDotPath))
                        throw new Exception("缺少文件，请尝试将项目[data/]中的所有文件复制到[bin/data/]中");
                }),
                new Tuple<string, string, Action>("检测文件..", "配置文件中没有内容，请联系管理员", () =>
                {
                    if(string.IsNullOrWhiteSpace(System.IO.File.ReadAllText(LocalFile.ConfigPath, Encoding.UTF8)))
                        throw new Exception($"配置文件[{LocalFile.ConfigPath}]中没有内容");
                }),
                new Tuple<string, string, Action>("初始化数据中..", "初始化数据库失败，请联系管理员", () =>
                {
                    AuthDb.Ini();
                    DataDb.Inidata();

                    //var dt = DateTime.Now;
                    //var data = new BoxInfo()
                    //{
                    //Num = 1,
                    //State = "ng1",
                    //IsOk=false,
                    //Time = dt,
                    //};
                    //AuthDb.dbBox.Insertable(data).ExecuteCommand();
                    //var info = AuthDb.dbBox.Queryable<BoxInfo>().Where(o => o.Id != 0).ToList();
                    //WarnInfoDb.Ini();
                }),
                //new Tuple<string, string, Action>("初始化RFID中..", "RFID连接失败，请检查串口", () =>
                //{

                //}),
                //new Tuple<string, string, Action>("连接机器人中..", "机器人连接失败，请检查是否打开软件", () =>
                //{

                //}),
                new Tuple<string, string, Action>("连接串口中..", "串口连接失败，请检查网络", () =>
                {

                    LocalStatic.Electric = new DianQiBan(LocalFile.Config.Electric);
                    LocalStatic.Test = new CeShiBan[]
                    {
                        new CeShiBan(LocalFile.Config.Text1),
                        new CeShiBan(LocalFile.Config.Text2),
                        new CeShiBan(LocalFile.Config.Text3),
                        new CeShiBan(LocalFile.Config.Text4),
                    };
                    LocalStatic.Change1 = new ChangeBan(LocalFile.Config.Change1);
                    LocalStatic.Change2 = new ChangeBan(LocalFile.Config.Change2);
                    //var res=LocalStatic.Electric.Open();
                    //LocalStatic.Plc = new SiemensS7Client(SiemensVersion.S7_1200,ipPort.Address,ipPort.Port);
                    //var res=LocalStatic.Plc.Open();
                    //if (!res.IsSucceed)
                    //    throw new Exception(res.Err);
                }),
                new Tuple<string, string, Action>("连接视觉中..", "视觉连接失败，请检查网络", () =>
                {
                    //var ipPort1 = LocalFile.Config.Vision1.ToIpPort();
                    //LocalStatic.Vision1 = new VisionBan(ipPort1.Address,ipPort1.Port);
                    ////var res=LocalStatic.Vision1.Open();
                    ////if (!res.IsSucceed)
                    ////    throw new Exception(res.Err);
                    //var ipPort2 = LocalFile.Config.Vision2.ToIpPort();
                    //LocalStatic.Vision2 = new VisionBan(ipPort2.Address,ipPort2.Port);
                    //var res1=LocalStatic.Vision2.Open();
                    //if (!res1.IsSucceed)
                    //    throw new Exception(res1.Err);
                }),
            };

            MainLoadWindow.TaskSleepTime = 200;
            if (!MainLoadWindow.Show(tuples))
                return false;

            //清理日志
            Task.Run(() =>
            {
                if (LocalFile.Config.Sys.SaveLogDay < 0)
                    return;

                var t = TimeSpan.FromDays(LocalFile.Config.Sys.SaveLogDay);
                Logs.Clear(t);
                WarnInfoDb.Clear(t);
            });

            //json转换器
            {
                //JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                //{
                //    Converters = new[] { new JsonDateTimeConverter() },
                //};
            }

            //不登录，直接使用最高权限
            {
                UserLoginView.NotLogin();
                return true;
            }
            //登录
            {
                //var userLoginView = new UserLoginView();
                //var isok = userLoginView.ShowDialog() == true;
                //userLoginView = null;
                //return isok;
            }
        }

        /// <summary>
        /// 初始化并运行时间
        /// </summary>
        public async void Init(System.Windows.Window window)
        {
            //加载 程序名称
            var versionInfo = FileVersionInfo.GetVersionInfo(LocalFile.AppPath);
            Title = $"{versionInfo.ProductName}  V{Version.Parse(versionInfo.FileVersion).ToString(2)}";
            //Title = $"显示板自动检测程序 V{ Version.Parse(versionInfo.FileVersion).ToString(2)}";

            //加载 窗体模式
            if (LocalFile.Config.Sys.StartupFull)
                window.WindowState = System.Windows.WindowState.Maximized;

            //注册 设备
            IotDevice.UserChange = ((iot) =>
            {
                if (string.IsNullOrEmpty(iot.Funct))
                    Growl.Info($"你点击了[{iot.Name}]，尝试改为[{iot.Val}]");
                else
                    Growl.Info($"你点击了[{iot.Name}][{iot.Funct}]，尝试改为[{iot.Val}]");

                Logs.Write(iot, LogsType.DeviceHand);
            });

            //注册 日志
            TextBoxLog.TextBoxLogAdd = ((info) =>
            {
                if (info.Tag is LogsType logsType)
                    Logs.Write(info.Text, logsType, info.Time);
                else
                    Logs.Write(info.Text, LogsType.Info, info.Time);
            });

            //加载 时钟
            while (true)
            {
                Time = DateTime.Now;
                await Task.Delay(1000);
            }
        }

        public ICommand OpenUserCommand { get => new DelegateCommand(OpenUser); }
        /// <summary>
        /// 打开用户
        /// </summary>
        public void OpenUser()
        {
            if (UserInfoView.viewModel.IsLogin)
            {
                var userInfoView = new UserInfoView();
                userInfoView.ShowDialog();

                if (userInfoView.IsExitLogin)
                {
                    Growl.Info("您已退出登录。");
                    userInfoView = null;
                }
            }
            else
            {
                var userLoginView = new UserLoginView();

                //登录成功
                if (userLoginView.ShowDialog() == true)
                {
                    Growl.Success($"欢迎您：{UserInfoView.viewModel.LoginName}");
                    userLoginView = null;
                }
            }
        }

        public ICommand OpenLogCommand { get => new DelegateCommand(OpenLog); }
        /// <summary>
        /// 打开日记
        /// </summary>
        public void OpenLog()
        {
            if (!System.IO.Directory.Exists(LocalFile.LogDir))
            {
                Growl.Info("暂时没有日志。");
                return;
            }

            try
            {
                Folder.OpenFolder(LocalFile.LogDir);
            }
            catch (Exception)
            {
                Growl.Error("打开日志目录失败。");
            }
        }

        public ICommand OpenHelpCommand { get => new DelegateCommand(OpenHelp); }
        /// <summary>
        /// 打开帮助
        /// </summary>
        public void OpenHelp()
        {
            if (!System.IO.File.Exists(LocalFile.DocPath))
            {
                Growl.Info("帮助文档正在书写中。");
                return;
            }

            try
            {
                Folder.OpenFolderAndSelectedFile(LocalFile.DocPath);
            }
            catch (Exception)
            {
                Growl.Error("打开帮助文档失败。");
            }
        }

        public ICommand OpenWeCommand { get => new DelegateCommand(OpenWe); }
        /// <summary>
        /// 打开关于
        /// </summary>
        public void OpenWe()
        {
            var aboutView = new AboutView();
            aboutView.ShowDialog();
            aboutView = null;
        }
    }
}
